// pages/my/my.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    openId:'',
    headImgUrl:'../images/head/headimage.jpeg',
    nickName:'这是昵称',
    phone:'0',
    userInfo: {},
    a:"",
    isShow:true,
    showActionsheet: false,
    groups: [
      { text: '退出登录',  type: 'warn', value: 1 }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getuser()
  },
  getuser(){
    // 查看是否授权
    wx.getSetting({
      success:(res)=> {
        console.log(res);
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: (res) =>{
              console.log(res.userInfo)
              console.log("成功");
              this.setData({
                isShow:false
              })
              this_.login();
              //用户已经授权过
            }
          })
        }else{
          console.log("失败")
          this.setData({
            isShow:true
          })
        }
      }
    })
    var this_ = this;
    wx.getUserInfo({
      success: (res) => {
        this_.setData({
          "userInfo":res.userInfo,
           headImgUrl:res.userInfo.avatarUrl,
           nickName:res.userInfo.nickName
        })
      },
    })

  },
  //绑定的是否登录授权的事件
  isGetinfo(data) {
    if (data.detail.rawData) {
      //点击了允许
      console.log("允许");
      this.getuser();

    } else {
      //点击了不允许
      console.log("不");
    }
  },
  //登录事件
  login(){
    //获取当前对象
    let this_ = this;
    // 登录
    wx.login({
      //接口成功调用的回调函数
      success: (r) => {
        //获取code
        var code = r.code;
        //根据code进行访问后台
        if (code) {
          //发送code到后台，分析openid
          wx.request({
            url: 'http://localhost:8060/user/login?code=' + code,
            method: 'POST',
            header: {
              'content-type': 'application/json'
            },
            //访问成功的回调函数
            success:(res)=>{
              //debugger;
              if (res.data.status == 200) {
                // 表示登录成功
               // >> 1、小程序客户端保存登录状态，即ticket  缓存
                wx.setStorage({
                  key: 'ticket',
                  data: res.data.ticket,
                })
                //后台传回来的openid
                let openId = res.data.openId;
                //后台传回来的用户状态
                let a = res.data.a;
                //后台传回的对象
                let userInfo = res.data.userInfo;
                console.info("userInfo是",userInfo)
                console.info("a是"+a)
                console.info(openId)
                if (a) {//判断对象是否为空 不为空时把对象信息赋值到页面 为空时注册
                  this_.setData({
                    openId:openId,
                    a:a,
                    headImgUrl:userInfo.headimgurl,
                    nickName:userInfo.nickname,
                    userInfo:userInfo
                  })
                  //把对象放入本地缓存 有用户且登录成功的
                  console.info(userInfo)
                  //缓存openId
                  wx.setStorageSync('openId', openId);
                  //将查询到的就诊数据放在缓存中
                  wx.setStorageSync('status3', res.data.userInfo.status);
                  wx.setStorageSync('id3', res.data.userInfo.id);
                  wx.setStorageSync('userName3', res.data.userInfo.username);
                  wx.setStorageSync('phone3', res.data.userInfo.phone);
                  wx.setStorageSync('idCard3', res.data.userInfo.idcard);
                  //缓存登陆成功的用户信息
                  wx.setStorage({
                    data: userInfo,
                    key: 'userInfo',
                  })
                  //缓存带有userId 的sessionId
                  wx.setStorage({
                    data:res.data.userSession,
                    key: 'userSession',
                  })
                }else{
                  this_.setData({
                    openId:openId,
                    a:a
                  })
                }
                
                //注册用户 以作判断 用户为空时注册
                this_.zhuce();
                console.info(openId)
                console.info(a)
                // >> 2、显示登录成功的信息
                wx.showToast({
                  title: '登录成功',
                  icon: 'success',
                  duration: 2000
                })
              } else {
                 // 登录失败
                 // >> 1、移除已经保存的ticket
                 wx.removeStorage({
                  key: 'key'
                 })
                // >> 2、显示登录失败信息
                wx.showToast({
                   title: '登录失败',
                   icon: 'none',
                  duration: 2000
                })
              }                   
            }
          })
        }
      }
    })
  },
  //注册方法
  zhuce(){
    let a = this.data.a;
    let this_ = this;
    if(!a){
      wx.request({   
        url: 'http://localhost:8060/user/register',
        method: 'POST',
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: { 
          openId:this_.data.openId,
          headImgUrl:this_.data.userInfo.avatarUrl,
          nickName:this_.data.userInfo.nickName,
          sex:this_.data.userInfo.gender
       },
        success(responseData){
          let result = responseData.data.addStatus;
          let userInfo = responseData.data.userInfo;
          console.info(userInfo)
          //注册完毕后返回用户 新用户
          wx.setStorage({
            data: userInfo,
            key: 'userInfo',
          })
          console.info(result)

        }
      })
    }
  },
  showUser(){
    let this_ = this;
    let openId = this.data.openId;
    if (openId!=null && openId!="") {
      wx.request({
        url: 'http://localhost:8060/user/getUser',
        method: 'POST',
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: { 
          openId:this.data.openId
        },
        success(responseData){
          this_.setData({
            headImgUrl:responseData.data.userInfo.headImgUrl,
            nickName:responseData.data.userInfo.nickName
          })
        }
      })
    } 
  },


  //用户点击授权
  shouQuan(){
    let this_ = this;
    let openId = this.data.openId;
    if (openId!=null || openId!="") {
      wx.request({
        url: 'http://localhost:8060/user/author',
        method: 'POST',
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: { 
          openId:this.data.openId
        },
        success(responseData){
          this_.setData({
            //修改手机号为授权的手机号
            phone:responseData.data.userInfo.phone
          })
        }
      })
    }
  },
  open: function(){
    this.setData({
      showActionsheet: true
  })
  },
  //点击头部
  clickHead(e){
    let phone_ = e.currentTarget.dataset.text
    if(phone_ != "0"){
      this.open()
    }else{
      wx.navigateTo({
        url: '/pages/middle/middle',
      })
    }
    
  },
  close: function () {
    this.setData({
        showActionsheet: false
    })
  },
  btnClick(e) {
    this.close()
    console.info("点击了退出登录")
  },

  //点击就诊人管理
  manage(e){
    //从缓存中获取用户的openid
    let openid = wx.getStorageSync('openId');
    console.log("缓存中的openId"+openid);
    if(openid != '' && openid != null){
      wx.request({
        url: 'http://localhost:8060/user/queryStatus',
        method: 'POST',
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: {
          openid
        },
        success(responseData){
          let status = responseData.data.infoStatus;
          console.log(status);
          if(status == 1){
            //用户就诊信息已存在
            wx.navigateTo({
              url: '../add/manage/manage',
            })
  
          }else if(status == 0){
            //用户信息不存在
            wx.navigateTo({
              url: '../add/addpage/addpage',
            })
          }else{
            //特殊情况。。。提示报错吧
            wx.showToast({
              title: '出现不可预知的错误，请退出重试！',
              icon: 'none'
            })
          }
  
        }
      });
    }else{
      wx.showToast({
        title: '请登录后再进行操作',
        icon: 'none'
      })
    }  
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.showUser()
  },
  
})